<template>
  <!-- 可移动的AI客服浮球 -->
  <div
    v-if="!isChatOpen"
    class="ai-chat-bubble"
    :style="bubbleStyle"
    @mousedown="startDrag"
    @click="toggleChat"
  >
    <div class="bubble-icon">
      <i class="el-icon-chat-dot-round"></i>
    </div>
    <div class="bubble-text">AI助手</div>
    <div v-if="unreadCount > 0" class="unread-badge">{{ unreadCount }}</div>
  </div>

  <!-- AI对话窗口 -->
  <div
    v-if="isChatOpen"
    class="ai-chat-window"
    :style="windowStyle"
  >
    <!-- 标题栏 -->
    <div class="chat-header" @mousedown="startDrag">
      <div class="header-title">
        <i class="el-icon-chat-dot-round"></i>
        <span>AI智能助手</span>
      </div>
      <div class="header-actions">
        <el-button
          type="text"
          icon="el-icon-minus"
          @click="minimizeChat"
          title="最小化"
        ></el-button>
        <el-button
          type="text"
          icon="el-icon-close"
          @click="closeChat"
          title="关闭"
        ></el-button>
      </div>
    </div>

    <!-- 消息列表 -->
    <div class="chat-messages" ref="messagesContainer">
      <!-- 欢迎消息 -->
      <div v-if="messages.length === 0" class="welcome-message">
        <div class="welcome-icon">👋</div>
        <div class="welcome-text">您好！我是AI智能助手</div>
        <div class="welcome-desc">有什么可以帮助您的吗？</div>
      </div>

      <!-- 对话消息 -->
      <div
        v-for="(msg, index) in messages"
        :key="index"
        :class="['message-item', msg.role === 'user' ? 'user-message' : 'ai-message']"
      >
        <div class="message-avatar">
          <i :class="msg.role === 'user' ? 'el-icon-user' : 'el-icon-chat-dot-round'"></i>
        </div>
        <div class="message-content">
          <div class="message-bubble">
            <div v-if="msg.isTyping" class="typing-indicator">
              <span></span><span></span><span></span>
            </div>
            <div v-else v-html="formatMessage(msg.content)"></div>
          </div>
          <div class="message-time">{{ msg.time }}</div>
        </div>
      </div>

      <!-- 加载中 -->
      <div v-if="isLoading" class="message-item ai-message">
        <div class="message-avatar">
          <i class="el-icon-chat-dot-round"></i>
        </div>
        <div class="message-content">
          <div class="message-bubble">
            <div class="typing-indicator">
              <span></span><span></span><span></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="2"
        placeholder="输入您的问题..."
        @keydown.enter.exact.prevent="sendMessage"
        @keydown.ctrl.enter="inputMessage += '\n'"
        :disabled="isLoading"
      ></el-input>
      <div class="input-actions">
        <div class="input-hint">
          <span>Enter 发送</span>
          <span>Ctrl+Enter 换行</span>
        </div>
        <el-button
          type="primary"
          icon="el-icon-s-promotion"
          @click="sendMessage"
          :loading="isLoading"
          :disabled="!inputMessage.trim()"
        >
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();

// 状态管理
const isChatOpen = ref(false);
const isDragging = ref(false);
const messages = ref([]);
const inputMessage = ref('');
const isLoading = ref(false);
const unreadCount = ref(0);

// 位置状态
const position = reactive({
  x: window.innerWidth - 100,
  y: window.innerHeight - 100,
  startX: 0,
  startY: 0,
  offsetX: 0,
  offsetY: 0
});

// 消息容器引用
const messagesContainer = ref(null);

// 当前流式响应的消息索引
let currentStreamingMessageIndex = -1;

/**
 * 浮球样式
 */
const bubbleStyle = computed(() => ({
  right: `${window.innerWidth - position.x - 80}px`,
  bottom: `${window.innerHeight - position.y - 80}px`,
  cursor: isDragging.value ? 'grabbing' : 'grab'
}));

/**
 * 窗口样式
 */
const windowStyle = computed(() => ({
  right: `${window.innerWidth - position.x - 400}px`,
  bottom: `${window.innerHeight - position.y - 600}px`
}));

/**
 * 开始拖拽
 */
const startDrag = (e) => {
  isDragging.value = true;
  position.startX = e.clientX;
  position.startY = e.clientY;
  position.offsetX = position.x;
  position.offsetY = position.y;

  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
  e.preventDefault();
};

/**
 * 拖拽中
 */
const onDrag = (e) => {
  if (!isDragging.value) return;
  
  const deltaX = e.clientX - position.startX;
  const deltaY = e.clientY - position.startY;
  
  position.x = Math.max(0, Math.min(window.innerWidth - 80, position.offsetX + deltaX));
  position.y = Math.max(0, Math.min(window.innerHeight - 80, position.offsetY + deltaY));
};

/**
 * 停止拖拽
 */
const stopDrag = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
};

/**
 * 切换聊天窗口
 */
const toggleChat = () => {
  if (isDragging.value) return;
  isChatOpen.value = !isChatOpen.value;
  unreadCount.value = 0;
  if (isChatOpen.value) {
    nextTick(() => {
      scrollToBottom();
    });
  }
};

/**
 * 最小化
 */
const minimizeChat = () => {
  isChatOpen.value = false;
};

/**
 * 关闭聊天
 */
const closeChat = () => {
  isChatOpen.value = false;
};

/**
 * 格式化消息（支持markdown简单渲染）
 */
const formatMessage = (content) => {
  if (!content) return '';
  
  // 简单的markdown渲染
  return content
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // 加粗
    .replace(/\*(.*?)\*/g, '<em>$1</em>') // 斜体
    .replace(/\n/g, '<br>'); // 换行
};

/**
 * 滚动到底部
 */
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

/**
 * 获取当前时间
 */
const getCurrentTime = () => {
  const now = new Date();
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
};

/**
 * 发送消息
 */
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return;

  const userMessage = inputMessage.value.trim();
  inputMessage.value = '';

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: userMessage,
    time: getCurrentTime()
  });

  scrollToBottom();
  isLoading.value = true;

  try {
    // 准备对话历史（最近10条）
    const conversationHistory = messages.value.slice(-10).map(m => ({
      role: m.role,
      content: m.content
    }));

    console.log('📤 发送消息到AI服务...', conversationHistory);

    // 调用后端API（流式响应）
    const response = await fetch(`${proxy.http.baseUrl}/api/AiChat/chat`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('Token')}`
      },
      body: JSON.stringify({
        messages: conversationHistory
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // 创建AI消息占位符
    currentStreamingMessageIndex = messages.value.length;
    messages.value.push({
      role: 'assistant',
      content: '',
      time: getCurrentTime(),
      isTyping: false
    });

    scrollToBottom();

    // 读取流式响应
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      
      if (done) {
        console.log('✅ AI响应完成');
        break;
      }

      // 解码数据
      buffer += decoder.decode(value, { stream: true });
      
      // 按行处理
      const lines = buffer.split('\n');
      buffer = lines.pop() || ''; // 保留未完成的行

      for (const line of lines) {
        if (!line.trim() || !line.startsWith('data:')) continue;
        
        const data = line.substring(5).trim(); // 去掉 "data:" 前缀
        
        if (data === '[DONE]') {
          console.log('🏁 收到结束标记');
          continue;
        }

        try {
          const parsed = JSON.parse(data);
          
          // 检查是否有错误
          if (parsed.error) {
            throw new Error(parsed.error.message);
          }

          // 提取内容
          if (parsed.choices && parsed.choices[0]?.delta?.content) {
            const content = parsed.choices[0].delta.content;
            messages.value[currentStreamingMessageIndex].content += content;
            scrollToBottom();
          }
        } catch (parseError) {
          console.warn('⚠️ 解析数据失败:', data, parseError);
        }
      }
    }

    // 标记完成
    if (currentStreamingMessageIndex >= 0) {
      messages.value[currentStreamingMessageIndex].isTyping = false;
    }

    // 如果窗口未打开，增加未读计数
    if (!isChatOpen.value) {
      unreadCount.value++;
    }

  } catch (error) {
    console.error('❌ 发送消息失败:', error);
    ElMessage.error(`发送失败: ${error.message}`);
    
    // 添加错误消息
    messages.value.push({
      role: 'assistant',
      content: `抱歉，我遇到了一些问题：${error.message}。请稍后再试。`,
      time: getCurrentTime()
    });
  } finally {
    isLoading.value = false;
    scrollToBottom();
  }
};

/**
 * 组件挂载
 */
onMounted(() => {
  console.log('🤖 AI客服组件已加载');
  
  // 初始位置（右下角）
  position.x = window.innerWidth - 100;
  position.y = window.innerHeight - 100;
});

/**
 * 组件卸载
 */
onUnmounted(() => {
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
});

defineExpose({
  toggleChat,
  sendMessage
});
</script>

<style lang="less" scoped>
/* 浮球样式 */
.ai-chat-bubble {
  position: fixed;
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 9999;
  user-select: none;

  &:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 30px rgba(102, 126, 234, 0.6);
  }

  &:active {
    transform: scale(0.95);
  }

  .bubble-icon {
    font-size: 32px;
    margin-bottom: 4px;
  }

  .bubble-text {
    font-size: 12px;
    font-weight: 500;
  }

  .unread-badge {
    position: absolute;
    top: 5px;
    right: 5px;
    background: #f56c6c;
    color: white;
    border-radius: 10px;
    padding: 2px 6px;
    font-size: 12px;
    font-weight: bold;
    min-width: 20px;
    text-align: center;
  }
}

/* 聊天窗口 */
.ai-chat-window {
  position: fixed;
  width: 400px;
  height: 600px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 40px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  z-index: 9999;
  overflow: hidden;

  /* 标题栏 */
  .chat-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 16px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: move;
    user-select: none;

    .header-title {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 16px;
      font-weight: 600;

      i {
        font-size: 20px;
      }
    }

    .header-actions {
      display: flex;
      gap: 8px;

      :deep(.el-button) {
        color: white;
        font-size: 18px;
        padding: 4px;

        &:hover {
          background: rgba(255, 255, 255, 0.2);
        }
      }
    }
  }

  /* 消息列表 */
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f5f7fa;

    /* 欢迎消息 */
    .welcome-message {
      text-align: center;
      padding: 40px 20px;

      .welcome-icon {
        font-size: 48px;
        margin-bottom: 16px;
      }

      .welcome-text {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 8px;
      }

      .welcome-desc {
        font-size: 14px;
        color: #909399;
      }
    }

    /* 消息项 */
    .message-item {
      display: flex;
      margin-bottom: 20px;
      animation: slideIn 0.3s ease;

      .message-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
        flex-shrink: 0;
      }

      .message-content {
        max-width: 70%;
        margin: 0 12px;

        .message-bubble {
          background: white;
          padding: 12px 16px;
          border-radius: 12px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
          word-wrap: break-word;
          line-height: 1.6;

          :deep(strong) {
            font-weight: 600;
            color: #303133;
          }

          :deep(em) {
            font-style: italic;
            color: #606266;
          }
        }

        .message-time {
          font-size: 12px;
          color: #909399;
          margin-top: 4px;
          padding: 0 4px;
        }
      }

      /* 用户消息 */
      &.user-message {
        flex-direction: row-reverse;

        .message-avatar {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
        }

        .message-content {
          .message-bubble {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
          }

          .message-time {
            text-align: right;
          }
        }
      }

      /* AI消息 */
      &.ai-message {
        .message-avatar {
          background: #e4e7ed;
          color: #606266;
        }
      }
    }

    /* 打字动画 */
    .typing-indicator {
      display: flex;
      gap: 4px;

      span {
        width: 8px;
        height: 8px;
        background: currentColor;
        border-radius: 50%;
        animation: typing 1.4s infinite;

        &:nth-child(2) {
          animation-delay: 0.2s;
        }

        &:nth-child(3) {
          animation-delay: 0.4s;
        }
      }
    }
  }

  /* 输入区域 */
  .chat-input {
    border-top: 1px solid #e4e7ed;
    padding: 16px 20px;
    background: white;

    :deep(.el-textarea__inner) {
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      padding: 10px;
      resize: none;

      &:focus {
        border-color: #667eea;
      }
    }

    .input-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 12px;

      .input-hint {
        font-size: 12px;
        color: #909399;
        display: flex;
        gap: 12px;
      }

      .el-button {
        border-radius: 8px;
      }
    }
  }
}

/* 动画 */
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes typing {
  0%, 60%, 100% {
    opacity: 0.3;
    transform: translateY(0);
  }
  30% {
    opacity: 1;
    transform: translateY(-6px);
  }
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;

  &:hover {
    background: #c0c4cc;
  }
}
</style>

